import { h, computed } from 'vue'
import './index.css'

export default (rawProps, { emit, attrs }) => {
  const props = {
    total: rawProps.total ?? 0,
    page: rawProps.page ?? 1,
    limit: rawProps.limit ?? 10,
    pageSizes: rawProps.pageSizes ?? [10, 20, 30, 50],
    pagerCount:
      rawProps.pagerCount ?? (document.body.clientWidth < 992 ? 5 : 7),
    layout:
      rawProps.layout ?? 'total, prev, pager, next, jumper',
    background: rawProps.background ?? true,
    autoScroll: rawProps.autoScroll ?? true,
    hidden: rawProps.hidden ?? false,
  }

  const currentPage = computed({
    get: () => props.page,
    set: val => emit?.('update:page', val),
  })

  const pageSize = computed({
    get: () => props.limit,
    set: val => emit?.('update:limit', val),
  })

  const handleSizeChange = (val) => {
    if (currentPage.value * val > props.total) {
      currentPage.value = 1
    }
    emit?.('pagination', { page: currentPage.value, limit: val })
  }

  const handleCurrentChange = (val) => {
    emit?.('pagination', { page: val, limit: pageSize.value })
  }

  const containerClass = {
    'pagination-container': true,
    hidden: props.hidden,
  }

  return (
    <div class={containerClass}>
      <el-pagination
        background={props.background}
        currentPage={currentPage.value}
        pageSize={pageSize.value}
        layout={props.layout}
        pageSizes={props.pageSizes}
        pagerCount={props.pagerCount}
        total={props.total}
        onSizeChange={handleSizeChange}
        onCurrentChange={handleCurrentChange}
      />
    </div>
  )
}
